using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class Rock : MonoBehaviour
{
    private Rigidbody rb;
    [Header("Base Settings")]
    public float force;
    public int damage;
    public GameObject target;
    private Vector3 direction;
    public enum RockStates { HitPlayer, HitEnemy, HitNothing }
    public RockStates rockState;
    public GameObject breakEffect;
    /// <summary>
    /// 未击中目标时，达到固定时间后消失
    /// </summary>
    public float lifeCounter;
    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.velocity = Vector3.one;
        rockState = RockStates.HitPlayer;
        FlyToTarget();
    }
    private void FixedUpdate()
    {
        if (rb.velocity.sqrMagnitude <= 10)
        {
            rockState = RockStates.HitNothing;
        }
        if (rockState == RockStates.HitNothing)
        {
            lifeCounter -= Time.deltaTime;
            if (lifeCounter <= 0)
            {
                Destroy(gameObject);
            }
        }
    }
    public void FlyToTarget()
    {
        if (target == null)
        {
            target = FindObjectOfType<playerController>().gameObject;
        }
        direction = (target.transform.position - transform.position + Vector3.up).normalized;
        rb.AddForce(direction * force, ForceMode.Impulse);
    }
    private void OnCollisionEnter(Collision other)
    {
        switch (rockState)
        {
            case RockStates.HitPlayer:
                if (other.gameObject.CompareTag("Player"))
                {
                    NavMeshAgent agent = other.gameObject.GetComponent<NavMeshAgent>();
                    agent.isStopped = true;
                    agent.velocity = force * direction;
                    other.gameObject.GetComponent<Animator>().SetTrigger("Dizzy");

                    var playerStat = other.gameObject.GetComponent<CharacterStats>();
                    playerStat.TakeDamage(damage, playerStat);

                    rockState = RockStates.HitNothing;
                }
                break;
            case RockStates.HitEnemy:
                var golem = other.gameObject.GetComponent<Golem>();
                if (golem != null)
                {
                    var golemStat = other.gameObject.GetComponent<CharacterStats>();
                    golemStat.TakeDamage(damage, golemStat);

                    Instantiate(breakEffect, transform.position, Quaternion.identity);
                    Destroy(gameObject);
                }
                break;
            case RockStates.HitNothing:
                break;
            default:
                break;
        }
    }
}
